package com.szcinda.rpa.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szcinda.rpa.Result;
import com.szcinda.rpa.service.JobDetailCreateDto;
import com.szcinda.rpa.service.JobDetailDto;
import com.szcinda.rpa.service.JobDetailService;
import com.szcinda.rpa.service.JobFileQuery;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/jobDetail")
public class TYJobLogController {

    @Value("${upload.file.path}")
    private String filePath;
    private final JobDetailService jobDetailService;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");

    public TYJobLogController(JobDetailService jobDetailService) {
        this.jobDetailService = jobDetailService;
    }

    @PostMapping("create")
    public Result<String> create(@RequestParam(value = "createDto") String orderCreateReqDto, @RequestParam(value = "file", required = false) MultipartFile[] files) throws Exception {
        JobDetailCreateDto createDto = objectMapper.readValue(orderCreateReqDto, JobDetailCreateDto.class);
        File path = new File(filePath);
        // 创建基础文件夹
        if (!path.exists()) {
            path.mkdirs();
        }
        String fileName;
        String fileSuffix;
        String nameNoSuffix;
        if (createDto.getInFiles() != null && createDto.getInFiles().size() > 0) {
            for (JobDetailCreateDto.File inFile : createDto.getInFiles()) {
                String originalFileName = inFile.getOriginalFileName();
                if (originalFileName != null && files != null && files.length > 0) {
                    for (MultipartFile file : files) {
                        String fileOriginalFilename = file.getOriginalFilename();
                        if (originalFileName.equals(fileOriginalFilename)) {
                            // 保存附件
                            //获取文件后缀名
                            nameNoSuffix = fileOriginalFilename.substring(0, fileOriginalFilename.lastIndexOf("."));
                            fileSuffix = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf("."));
                            //新生成文件名
                            fileName = nameNoSuffix + "-" + LocalDateTime.now().format(dateTimeFormatter) + fileSuffix;
                            fileName = fileName.replaceAll("#", "井");
                            inFile.setUuidName(fileName);
                            File newFile = new File(path, fileName);
                            file.transferTo(newFile);
                        }
                    }
                }
            }
        }
        if (createDto.getOutFiles() != null && createDto.getOutFiles().size() > 0) {
            for (JobDetailCreateDto.File outFile : createDto.getOutFiles()) {
                String originalFileName = outFile.getOriginalFileName();
                if (originalFileName != null && files != null && files.length > 0) {
                    for (MultipartFile file : files) {
                        String fileOriginalFilename = file.getOriginalFilename();
                        if (originalFileName.equals(fileOriginalFilename)) {
                            // 保存附件
                            //获取文件后缀名
                            //获取文件后缀名
                            nameNoSuffix = fileOriginalFilename.substring(0, fileOriginalFilename.lastIndexOf("."));
                            fileSuffix = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf("."));
                            //新生成文件名
                            fileName = nameNoSuffix + "-" + LocalDateTime.now().format(dateTimeFormatter) + fileSuffix;
                            fileName = fileName.replaceAll("#", "井");
                            outFile.setUuidName(fileName);
                            File newFile = new File(path, fileName);
                            file.transferTo(newFile);
                        }
                    }
                }
            }
        }
        jobDetailService.create(createDto);
        return Result.success();
    }

    @PostMapping("getFilePath")
    public Result<String> getFilePath(@RequestBody JobFileQuery query) {
        return Result.success(jobDetailService.getFilePathByParams(query));
    }

    @GetMapping("/search/{orderNo}")
    public Result<List<JobDetailDto>> search(@PathVariable String orderNo) {
        return Result.success(jobDetailService.queryByOrderNo(orderNo));
    }

    @GetMapping("searchNos/{params}")
    public Result<List<String>> searchNo(@PathVariable String params) {
        return Result.success(jobDetailService.queryNos(params));
    }

    @PostMapping("download")
    public void download(@RequestParam String fileName, HttpServletResponse response) throws Exception {
        File file = new File(filePath, fileName);
        String fName = URLEncoder.encode(file.getName());
        response.setHeader("Content-Disposition", "attachment;filename=" + fName);
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Length", "" + file.length());
        // 发送给客户端的数据
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (bis != null) {
                bis.close();
            }
            outputStream.close();
        }
    }


}
